package com.yeswater.multithread.chapter7;

/**
 * author： yeswater
 * create： 2023/11/8
 * <p>
 * 重写 ThreadGroup 的 uncaughtException(), 加入interrupt()
 *  可以达到效果：在线程组中的一个线程出现异常后，将其他线程全部停止！！
 */
public class Run_7_8_2 {
    public static void main(String[] args) {
        ThreadGroup1 group = new ThreadGroup1("my-thread-group");
        Thread1[] thread1s = new Thread1[10];
        
        for (int i = 0; i < thread1s.length; i++) {
            thread1s[i] = new Thread1(group, "线程" + (i + 1), "1");
            thread1s[i].start();
        }
        
        Thread1 newT = new Thread1(group, "报错线程", "a");
        newT.start();
    }
    
    private static class Thread1 extends Thread {
        private String num;
        
        public Thread1(ThreadGroup group, String name, String num) {
            super(group, name);
            this.num = num;
        }
        
        @Override
        public void run() {
            int numInt = Integer.parseInt(num);
            while (!this.isInterrupted()) {
                System.out.println("死循环中：" + Thread.currentThread().getName());
            }
        }
    }
    
    private static class ThreadGroup1 extends ThreadGroup {
        public ThreadGroup1(String name) {
            super(name);
        }
        
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            super.uncaughtException(t, e);
            System.out.println("interrupt");
            this.interrupt();  // 这里 this 代表的是线程组
        }
    }
}
